package uploadfiletoserver;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

public class UploadFile {
    public static void uploadFile(String address, int port, String username, String password, String email, List<String> fileToSend){
        FTPClient ftpClient = new FTPClient();
        try {
            //连接FTP服务器
            ftpClient.connect(address,port);
            //登录FTP服务器
            ftpClient.login(username,password);
            ftpClient.setControlEncoding("UTF-8");
            //每次数据连接之前ftp client告诉ftp server开通 一个端口来传输数据。
            ftpClient.enterLocalPassiveMode();
            //写入方式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            for (String file : fileToSend) {
                File files = new File(file);
                FileInputStream inputStream = new FileInputStream(files);
                //将流写入服务器
                boolean uploaded = ftpClient.storeFile(files.getName(), inputStream);
                inputStream.close();

                if(uploaded){
                    System.out.println("文件上传成功");
                }else {
                    System.out.println("文件上传失败");
                }
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(ftpClient.isConnected()){
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
